//网关签名
const
    shajs = require('./sha'),
    base64 = require('./base64');

//网关配置
const sign = (method, url, data) => {
    let app = getApp() || {},
        globalData = app.globalData || {},
        timeDiff = globalData.timeDiff || 0;

    let timestamp = Math.round((Date.now() - timeDiff) / 1000).toString();
    let p_arr = [],
        params = {  //网关固定配置参数
            appid: 112,
            nonce: '3451778',
            timestamp: `${timestamp}`
        };

    //格式转换
    for (let key in params) {
        p_arr.push(`${key}=${params[key]}`);
    }

    //网关配置
    if (method.toLowerCase() === 'get') {
        //链接传参
        if (url.indexOf('?') !== -1) {
            let params = url.split('?')[1];

            p_arr.push(...params.split('&'));
        } else {
            for (let key in data) {
                p_arr.push(`${key}=${data[key]}`);
            }
        }
    }

    p_arr.sort();

    let queryString = p_arr.join('&') + '&secret=9uCh4qxBlFqap/+KiqoM68EqO8yYGpKa1c+BCgkOEa4=';
    let sha = shajs.hex_sha1(queryString);

    params.sigture = base64.Base64.encode(sha);

    return params;
};

module.exports = {
    sign,
};